package com.gable.exhibition.util;

import com.gable.common.util.CacheData;
import com.gable.common.util.StringUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.CheckExeclDao;
import com.gable.exhibition.model.ContractDevice;
import com.gable.exhibition.model.ContractDeviceEstimateSend;
import com.gable.exhibition.model.ContractEstimateSend;
import com.gable.exhibition.view.ContractDeviceEstimateSendView;
import com.gable.exhibition.view.ContractEstimateSendView;
import com.gable.exhibition.view.ImportExcelEstimateModel;
import com.gable.exhibition.view.ImportExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Lesson on 2018/2/24.
 */
@Component
public class CheckImportExcelEstimate {

    @Autowired
    CheckExeclDao checkExeclDao;

    public static String [] properties = new String [] {
            "contractNo","deviceModel","estimateSendDate","estimateQuantityStr","remark"};

    private String REGNUMBER = "^[0-9]\\d*(\\.\\d{1,2})?$";

    private String REGINTEGER = "^\\+?[0-9]\\d*$";

    private String REGDATE = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$";



    //用户id作为key
    public static Map<Long,Object> resultMap = new ConcurrentHashMap<Long,Object>();


    public static Map<Long,Object> resultMap1 = new ConcurrentHashMap<Long,Object>();


    public ImportExcelView checkEstimate(List<ImportExcelEstimateModel> list){

        //给到客户端的数据集
        ImportExcelView iev = new ImportExcelView();

        //错误信息
        List<String> errorMessage = new ArrayList<String>();

        Map<String,Integer> contractNoDateMap = new HashMap<String,Integer>();

        Map<String,Integer> eMap = new HashMap<String,Integer>();

        int count=0;

        Map map = new HashMap();

        List<ContractEstimateSendView> cList = new ArrayList<ContractEstimateSendView>();

        List<ContractDeviceEstimateSend> eList = new ArrayList<ContractDeviceEstimateSend>();

        for (int i= 0; i< list.size(); i++){
            int row = i + 1;

            //校验合同是否存在
            if(StringUtil.isEmpty(list.get(i).getContractNo())){
                errorMessage.add("第"+row+"行，第"+queryProperties("contractNo")+"列的合同编号信息不能为空");
                count++;
            }else{
                Long id = checkExeclDao.queryContractIdByContractNo(list.get(i).getContractNo());
                if(id == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("contractNo")+"列的合同编号不存在");
                    count++;
                }
                list.get(i).setContractId(id);
            }

            //校验合同下的设备型号是否存在
            if(StringUtil.isEmpty(list.get(i).getDeviceModel())){
                errorMessage.add("第"+row+"行，第"+queryProperties("contractNo")+"列的设备型号不能为空");
                count++;
            }else{
                map.put("contractId",list.get(i).getContractId());
                map.put("deviceModel",list.get(i).getDeviceModel());
                ContractDevice contractDevice = checkExeclDao.queryContractDeviceByContractNoAndDevcieModel(map);
                if(contractDevice == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceModel")+"列的设备型号不存在");
                    count++;
                }else{
                    list.get(i).setContractDevice(contractDevice);
                }
            }

            //校验预计发货日期
            if(StringUtil.isEmpty(list.get(i).getEstimateSendDate())){
                errorMessage.add("第"+row+"行，第"+queryProperties("estimateSendDate")+"列的预计发货日期不能为空");
                count++;
            }else{
                boolean bl = CheckPattern(REGDATE,list.get(i).getEstimateSendDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("estimateSendDate")+"列的预计发货日期格式不正确");
                    count++;
                }
            }

            //校验预计发货数量
            if(StringUtil.isEmpty(list.get(i).getEstimateQuantityStr())){
                errorMessage.add("第"+row+"行，第"+queryProperties("estimateQuantityStr")+"列的预计发货数量不能为空");
                count++;
            }else{
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getEstimateQuantityStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("estimateQuantityStr")+"列的预计发货数量格式不正确");
                    count++;
                }else{
                    list.get(i).setEstimateQuantity(Integer.parseInt(list.get(i).getEstimateQuantityStr()));
                }
            }

            if(list.get(i).getContractDevice() != null && list.get(i).getEstimateQuantity() != null){
                int eSums = checkExeclDao.querystimateQuantity(list.get(i).getContractDevice().getContractDeviceId());
                int tQuantity = list.get(i).getContractDevice().getQuantity();
                int quantity = list.get(i).getEstimateQuantity();
                boolean bl = false;
                if((tQuantity-eSums) < quantity){
                    errorMessage.add("第"+row+"行，第"+queryProperties("estimateQuantityStr")+"列的预计发货数量大于该设备未预计发货数量");
                    count++;
                    bl= true;
                }

                String keys =list.get(i).getContractNo() +  list.get(i).getContractDevice().getContractDeviceId();
                if(eMap.containsKey(keys)){
                    int num = eMap.get(keys)+list.get(i).getEstimateQuantity();
                    eMap.put(keys,num);
                }else{
                    eMap.put(keys,list.get(i).getEstimateQuantity());
                }

                int toQuantity = eMap.get(keys);
                if((tQuantity-eSums) < toQuantity && !bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("estimateQuantityStr")+"列的预计发货数量大于该设备未预计发货数量");
                    count++;
                }
            }

            List<ContractEstimateSendView> cList1 = new ArrayList<ContractEstimateSendView>();
            List<ContractDeviceEstimateSend> eList1 = new ArrayList<ContractDeviceEstimateSend>();

            ContractEstimateSendView contractEstimateSend = new ContractEstimateSendView();
            contractEstimateSend.setContractId(list.get(i).getContractId());
            contractEstimateSend.setEstimateSendDate(list.get(i).getEstimateSendDate());
            contractEstimateSend.setRemark(list.get(i).getRemark());


            ContractDeviceEstimateSend contractDeviceEstimateSend = new ContractDeviceEstimateSend();
            contractDeviceEstimateSend.setContractDeviceId(list.get(i).getContractDevice().getContractDeviceId());
            contractDeviceEstimateSend.setEstimateQuantity(list.get(i).getEstimateQuantity());

            String key = list.get(i).getContractNo()+list.get(i).getEstimateSendDate();
            if(!contractNoDateMap.containsKey(key)){
                if(cList.size()==0){
                    cList = cList1;
                }
                cList.add(contractEstimateSend);
                eList = eList1;
                contractEstimateSend.setContractEstimateSendList(eList);
                eList.add(contractDeviceEstimateSend);
            }else{
                eList.add(contractDeviceEstimateSend);
            }
            contractNoDateMap.put(key,row);
        }

        if(count == 0){
            iev.setBool(true);
        }else{
            iev.setBool(false);
        }

        iev.setErrorMessage(errorMessage);
        resultMap1.put(CacheData.getSessionUser(null,1).getUserId(),cList);
        return iev;
    }

    //正则表达式
    private boolean  CheckPattern(String reg,String str){
        str = str .replaceAll("/","-");
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(str);
        boolean bl = matcher.matches();
        return bl;
    }

    //获取Properties数组字符串的下标
    private int queryProperties(String str){
        if(str == null || str.equals("")){
            return 0;
        }
        for(int i = 0;i<properties.length;i++){
            if(properties[i].equals(str)){
                int index = i+2;
                return index;
            }
        }
        return 0;
    }
}
